package com.king.freefish.online.service.impl;

import cn.hutool.core.lang.UUID;
import com.king.freefish.common.util.IpUtil;
import com.king.freefish.entity.OnlineUser;
import com.king.freefish.online.service.OnlineUserService;
import com.king.freefish.online.repository.OnlineUserRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @packageName com.king.freefish.online.service.impl
 * @author: jinguoguang
 * @date: 2025/7/29 15:05
 * @description:
 **/
@Service
@AllArgsConstructor
public class OnlineUserServiceImpl implements OnlineUserService {
    @Autowired
    private OnlineUserRepository onlineUserRepository;

    /**
     * 用户上线
     */
    @Override
    public String online(HttpServletRequest request) {
        // 生成唯一会话ID
        String sessionId = UUID.randomUUID().toString();

        // 获取用户IP
        String ip = IpUtil.getClientIpAddress(request);
        // 获取用户代理信息
        String userAgent = request.getHeader("User-Agent");
        // 创建在线用户对象
        OnlineUser user = new OnlineUser();
        user.setSessionId(sessionId);
        user.setIp(ip);
        user.setUserAgent(userAgent);
        user.setLoginTime(LocalDateTime.now());
        // 保存到Redis
        onlineUserRepository.online(user);
        return sessionId;
    }

    /**
     * 用户下线
     */
    @Override
    public void offline(String sessionId) {
        onlineUserRepository.offline(sessionId);
    }

    /**
     * 获取在线IP数量
     */
    @Override
    public Long getOnlineIpCount() {
        return onlineUserRepository.getOnlineIpCount();
    }

    /**
     * 获取在线会话数量
     */
    @Override
    public long getOnlineSessionCount() {
        return onlineUserRepository.getOnlineSessionCount();
    }

    /**
     * 清理过期会话
     */
    @Override
    public void cleanExpiredSessions() {
        onlineUserRepository.cleanExpiredSessions();
    }

}
